package com.k8sops.backend.filter;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义CORS过滤器，用于处理跨域请求
 * 优先级设置为最高，确保在其他过滤器之前处理CORS
 */
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CustomCorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        // 获取请求的Origin
        String origin = request.getHeader("Origin");
        
        // 如果Origin不为空，则设置允许该Origin访问
        if (origin != null) {
            response.setHeader("Access-Control-Allow-Origin", origin);
        }
        
        // 允许凭证
        response.setHeader("Access-Control-Allow-Credentials", "true");
        
        // 允许的请求方法
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH");
        
        // 允许的请求头
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, user_id");
        
        // 暴露的响应头
        response.setHeader("Access-Control-Expose-Headers", "Authorization, Content-Type, X-Requested-With, Accept, Origin, Access-Control-Request-Method, Access-Control-Request-Headers");
        
        // 预检请求的有效期，单位为秒
        response.setHeader("Access-Control-Max-Age", "3600");

        // 对于OPTIONS请求，直接返回200状态码
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            // 对于非OPTIONS请求，继续执行过滤器链
            chain.doFilter(req, res);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }
}
